<?php

namespace app\queue\stomp;

use common\model\OrderModel;
use Exception;
use support\bootstrap\Redis;
use Throwable;
use app\queue\BaseConsumer;
use common\service\OrderService;
use Webman\Stomp\Client;
use Webman\Stomp\RetryAbleConsumer;

/**
 * 设置订单工序任务执行人
 */
class SetTenantGroupStepTaskExecutorConsumer extends BaseConsumer implements RetryAbleConsumer
{
    // 要消费的队列名
    public $queue = 'set_tenant_group_step_task_executor';

    // 连接名，对应 config/redis_queue.php 里的连接`
    public $connection = 'default';

    public $lockKey = '';

    /**
     * @param $data
     * @return void
     * @throws Throwable
     */
    public function doConsume($data)
    {
        $order = model(OrderModel::class)->forceMasterDB()->find($data["order_id"]);
        $this->lockKey = "lock_order_send:to_tenant-{$order['to_tenant_id']}:project-{$order['project_id']}";
        if (Redis::get($this->lockKey)) {
            // 发现同项目 同租户 正在分发任务 吧当前生成任务 延期到下一次重试
            Client::send("set_tenant_group_step_task_executor",
                build_queue_data_with_xu(['order_id' => $data["order_id"],]), $this->getTtr());
            return;
        }
        // 设置锁标记 过期时间为队列执行时间
        Redis::setEx($this->lockKey, $this->getTtr(), 1);
        OrderService::getInstance()->setTenantGroupStepTaskExecutor($data["order_id"]);
        $this->removeLock();
    }

    /**
     * 移除锁
     * @return void
     */
    private function removeLock()
    {
        if (empty($this->lockKey)) {
            return;
        }
        Redis::del($this->lockKey);
    }

    /**
     * 重试间隔
     * @return int
     */
    public function getTtr()
    {
        return 30;
    }

    /**
     * 能否重试判断
     * @param int $attempt
     * @param Exception|Throwable $error
     * @return bool
     */
    public function canRetry($attempt, $error)
    {
        $this->removeLock();
        trace(format_exception_info($error), 'ERR');
        return $attempt < 3;
    }
}
